package com.gcph.zhuoba.util;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.common.Constant;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

/**
 * 异步下载图片
 * 
 * @author heroz
 *
 */
public class DownImage extends AsyncTask {
	public static Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private ImageView imageView;

	public DownImage(ImageView imageView) {
		this.imageView = imageView;
	}

	@Override
	protected Object doInBackground(Object... params) {
		String url = (String) params[0];
		return loadImageFromNetwork(url);
	}

	@Override
	protected void onPostExecute(Object result) {
		Drawable drawable = (Drawable) result;
		imageView.setImageDrawable(drawable);

	}

	/**
	 * 读取网络图片
	 * 
	 * @param imageUrl
	 * @return
	 */
	private Drawable loadImageFromNetwork(String imageUrl) {
		Drawable drawable = null;
		// 如果缓存过就从缓存中取出数据
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				L.d("从图片缓存中取出"+imageUrl);
				return softReference.get();
			}
		}
		
		//如果本地存储有这个文件，则直接从本地取
		String fileName = getFileNameFromUrl(imageUrl);
		String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+fileName;
		
		File file =new File(target);
		if(file.exists())
		{
			drawable = Drawable.createFromPath(target);
			L.d("从本地取得图片文件。。。。。");
			return drawable; 
		}
		
		try {

			drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.jpg");
			imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
			
			//下载缓存图片
			downLoadImage(imageUrl);
		} catch (IOException e) {
			Log.d("test", e.getMessage());
		}
		if (drawable == null) {
			Log.d("test", "null drawable");
		} else {
			Log.d("test", "not null drawable");
		}

		return drawable;
	}
	
	
	/**
	 * 根据url得文件名
	 * @param url
	 * @return
	 */
	public String getFileNameFromUrl(String url)
	{
		String fileName = url;
		if(null != url && url.contains("/"))
		{
			int index = url.lastIndexOf("/");
			fileName = url.substring(index);
		}
		return fileName;
	}
	
	/*
	 * 下载视频，并保存到存储卡
	 */
	public void downLoadImage(String remoteFileUrl)
	{
		HttpUtils http = new HttpUtils();
		//String url = Constant.server_root_url +remoteFileUrl;
		String fileName = getFileNameFromUrl(remoteFileUrl);
		String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+fileName;
		
		File file =new File(target);
		if(file.exists())
		{
			return ;
		}
		
        http.download(remoteFileUrl, target, true, true, new RequestCallBack<File>() {  
                    @Override  
                    public void onStart() {  
                    }  

                    @Override  
                    public void onLoading(long total, long current, boolean isUploading) {  
                    	int rate = (int) ((double) current/ (double) total *100);
                    }  

                    @Override  
                    public void onSuccess(ResponseInfo<File> responseInfo) { 
                    	L.d("下载图片成功====");
                    }  

                    @Override  
                    public void onFailure(HttpException error, String msg) {  
                    	 
                    }
                });  
	}

}
